/* eslint-disable */
import { message } from 'antd';
import memoryUtils from '@/utils/memoryUtils';

import { LEASE_HOURS } from '@/utils/constants';

// import "./baja.js";

const bajaPromise = window.bajaPromise;

const Baja = ()=> {
  if(!bajaPromise) {
    message.error('Baja() global bajaPromise is null!');
    return null;
  }
  return new Promise((resolve)=> {
    bajaPromise.then(baja=>{
      memoryUtils.user.username = baja.getUserName();
      resolve(baja);
    }).catch(error=>{
      message.error('Baja() error：' + error.message);
    });
  });
}

const makeOrd = (baja, ord)=>{
  return new Promise((resolve)=> {
    baja.Ord.make(ord).get({
      lease: true, // Temporarily subscribe the Counter for one minute.
      leaseTime: baja.RelTime.make({ hours: LEASE_HOURS })
    }).then(component => {
      resolve(component);
    }).catch(error => {
      message.error('makeOrd() error：' + error.message + ", " + ord);
    });
  })
}

const Ord = async (ord) => {
   const baja  = await Baja();
   if(baja) {
     const component = await makeOrd(baja, ord);
     return Promise.resolve(component);
   } else {
     message.error('Ord(): baja fetch failure!');
   }
}

const initTlsWebServer = async () => {
  const tlsWebServer = await Ord('station:|slot:/Services/TLSWebServer');
  memoryUtils.tlsWebServer = tlsWebServer;
  return Promise.resolve(tlsWebServer);
}

const fetchTlsWebServer = () => {
  const tlsWebServer = memoryUtils.tlsWebServer;
  if(tlsWebServer && tlsWebServer.$parent) {
    return tlsWebServer;
  } else {
    return initTlsWebServer();
  }
}

const fetchNavChildren = async (component) => {
  if(!component.$lease) {
    component = await Ord('station:|h:'+component.$handle);
  }
  const kids = await component.getNavChildren();
  if(kids) {
    for(let i=0;i<kids.length;i++) {
      if(!kids[i].$lease) {
        kids[i] = await Ord('station:|h:'+kids[i].$handle);
      }
    }
  }
  return Promise.resolve(kids);
}

const subscribeComp = async (ord, update) => {
  const baja  = await Baja();
  const sub = new baja.Subscriber();
  sub.attach('changed', function(prop) {
    //每次属性改变，都会回调
    update(this, prop);
  });
  //给组件添加订阅
  baja.Ord.make(ord).get({subscriber: sub}).then(component=>{
    update(component);
  });
  return Promise.resolve(sub);
}

export {Baja, Ord, initTlsWebServer, fetchTlsWebServer, fetchNavChildren, subscribeComp};
